/**
 * 用于 渲染订单卡片的组件，根据接收参数的不同渲染不同的订单卡片
 * type?：
 *     0：待付款
 *     1：已付款
 *     2：已发货
 *     3、4：已收货
 *     6：等待支付
 * orderData?：待付款、已付款、已发货、已收货 时传入的数据
 * afterVal?：售后 时传入的数据
 * changeFn?：点击我的订单 navbar 时候的函数，会刷新页面
 * orderId? 和 skuId?：在 退单 界面使用此组件时候需要传入的 参数
 **/
import React, { memo, useEffect, useState } from 'react'
import styles from './index.module.less'
import { cancelOrder, addConfirmOrder, receiveDone, deleteOrder, clearOrderFocus, getPreOrderById } from '@/utils/my/order'
import { Toast } from 'antd-mobile'
import { PictureWrongOutline } from 'antd-mobile-icons'

import { useNavigate } from 'react-router-dom'



type orderDatas = {
  order: {
    id: string
    orderSn: string
    modifyTime: string
    totalAmount: string
    status: string
  }
  items: [
    {
      id: string
      productName: string
      productPic: string
      productPrice: string | null
      productAttr: string
      productQuantity: string | number
      cartId: string
      productId: string
      productSkuId: string
      productSn: string
    }
  ]
}

interface orderType {
  type?: string
  orderData?: Array<{
    order: {
      id: string
      orderSn: string
      modifyTime: string
      totalAmount: string
      status: string
    },
    items: [
      {
        id: string
        productName: string
        productPic: string
        productPrice: string | null
        productAttr: string
        productQuantity: string | number
        cartId: string
        productId: string
        productSkuId: string
        productSn: string
        isReturn: number
      }
    ]
  }>
  afterVal?: Array<{
    orderSn: string
    productPic: string
    productName: string
    productPrice: string
    id: string
    productAttr: [
      { key: string, value: string },
      { key: string, value: string }
    ]
    createTime: string
    returnAmount: string
    productCount: string
    status: number
  }>
  changeFn?: (type: string) => Promise<void>
  orderId?: string
  skuId?: string
}

type orderItems = {
  id: string
  productName: string
  productPic: string
  productPrice: string | null
  // productAttr: string
  productQuantity: string | number
  cartId: string
  productId: string
  productSkuId: string
  productSn: string
  productAttr: [{}]
}



const OrderCard = memo(({ type, orderData, afterVal, changeFn, orderId, skuId }: orderType) => {

  console.log(orderData)


  const [orderDataCopy, setOrderDataCopy] = useState([{} as orderItems])

  const getOrderById = async (orderId: string) => {
    let res: resType = await getPreOrderById(orderId)
    if (res.code === 20000) {

      let obj = {} as orderDatas
      if (res.code === 20000) {
        const arr = res.data.orderItems.filter((item: { id: string }) => item.id === skuId)
        arr.forEach((item: { productAttr: string }) => item.productAttr = JSON.parse(item.productAttr))
        obj.items = arr[0]
        setOrderDataCopy(arr)
      }
    }
  }

  useEffect(() => {
    orderId && getOrderById(orderId)
  }, [])




  // --------------------------
  // --------------------------
  // --------------------------
  // --------------------------

  const navigate = useNavigate()

  const btnHandle = (code?: number, name?: string) => {
    if (code === 20000) {
      Toast.show({
        icon: 'success',
        content: `${name}成功`,
        duration: 800
      })
    } else {
      Toast.show({
        icon: 'fail',
        content: `${name}失败，请重试`,
        duration: 800
      })
    }
    type && changeFn && changeFn(type)
  }

  // 取消订单按钮
  const cancelGoods = async (val: orderDatas) => {
    let res: resType = await cancelOrder(val.order.id)
    btnHandle(res.code, '取消订单')
  }

  // 付款按钮
  const payBtn = (val: orderDatas) => {
    navigate(`/my/order/confirmorder?id=${val.order.id}`)
  }

  // 删除订单按钮
  const delGoods = async (val: orderDatas) => {
    let res: resType = await clearOrderFocus(val.order.id)
    btnHandle(res.code, '删除订单')
  }

  // 确认收货按钮
  const confirmGoods = async (val: orderDatas) => {
    let res: resType = await receiveDone({
      orderId: val.order.id
    })
    btnHandle(res.code, '确认收货')
  }

  // 确认付款按钮
  const confirmPay = (val: orderDatas) => {
    if (!localStorage.getItem('adress')) {
      Toast.show({
        content: '请选择邮寄地址！',
        duration: 800
      })
      return
    }

    let orderId = ''
    let addressId = JSON.parse(localStorage.getItem('adress') as string).id
    let orderItemList = [] as Array<object>
    orderId = val.order.id
    val.items.forEach(item => {
      const obj = {
        cartId: item.cartId,
        productId: item.productId,
        productQuantity: item.productQuantity,
        productSkuId: item.productSkuId,
      }
      orderItemList.push(obj)
    })
    sendOrder({
      orderId,
      addressId,
      orderItemList,
      'payType': 1,
      'sourceType': 1
    })
  }

  // ----------------------------------------------------------
  // ----------------------------------------------------------
  // 确认付款按钮
  const confirmPay1 = (val: orderDatas) => {
    if (!localStorage.getItem('adress')) {
      Toast.show({
        content: '请选择邮寄地址！',
        duration: 800
      })
      return
    }

    let orderId = ''
    let addressId = JSON.parse(localStorage.getItem('adress') as string).id
    let orderItemList = [] as Array<object>
    orderId = val.order.id
    val.items.forEach(item => {
      const obj = {
        cartId: item.cartId,
        productId: item.productId,
        productQuantity: item.productQuantity,
        productSkuId: item.productSkuId,
      }
      orderItemList.push(obj)
    })
    sendOrder1({
      orderId,
      addressId,
      orderItemList,
      'payType': 1,
      'sourceType': 1
    })
  }

  // 确认付款按钮
  const confirmPay2 = (val: orderDatas) => {
    if (!localStorage.getItem('adress')) {
      Toast.show({
        content: '请选择邮寄地址！',
        duration: 800
      })
      return
    }

    let orderId = ''
    let addressId = JSON.parse(localStorage.getItem('adress') as string).id
    let orderItemList = [] as Array<object>
    orderId = val.order.id
    val.items.forEach(item => {
      const obj = {
        cartId: item.cartId,
        productId: item.productId,
        productQuantity: item.productQuantity,
        productSkuId: item.productSkuId,
      }
      orderItemList.push(obj)
    })
    sendOrder2({
      orderId,
      addressId,
      orderItemList,
      'payType': 1,
      'sourceType': 1
    })
  }


  // 确认付款的发送的请求
  const sendOrder1 = async (sendObj: object) => {
    let res: resType = await addConfirmOrder(sendObj)
    if (res.code === 20000) {
      navigate(`/my/order/payment1?orderId=${res.data.orderId}`, { replace: true, state: res.data })
    }
  }
  // 确认付款的发送的请求
  const sendOrder2 = async (sendObj: object) => {
    let res: resType = await addConfirmOrder(sendObj)
    if (res.code === 20000) {
      navigate(`/my/order/payment2?orderId=${res.data.orderId}`, { replace: true, state: res.data })
    }
  }



  // ----------------------------------------------------------
  // ----------------------------------------------------------

  // 确认付款的发送的请求
  const sendOrder = async (sendObj: object) => {
    let res: resType = await addConfirmOrder(sendObj)
    if (res.code === 20000) {
      navigate(`/my/order/payment?orderId=${res.data.orderId}`, { replace: true, state: res.data })
    }
  }

  // 退货按钮 
  const returnGoods = (val: any) => {
    // 点击退货获取到的值
    console.log(val)
    // console.log('点击了退货按钮')
    navigate(`/my/order/orderBack?id=${val.orderId}&skuid=${val.id}`, { replace: false, state: val.productQuantity })
  }

  // 进入商品详情页面
  const gotoGoodsDetail = (item?: any) => {
    localStorage.setItem('type', '')
    navigate(`/cate/goodsdetail?productId=${item.productId}`)
  }


  const itemStatus = (status: number) => {
    switch (status) {
      case 0:
        return <div>等待处理</div>
      case 1:
        return <div>确认退货，等待用户发货</div>
      case 2:
        return <div style={{ color: '#f00' }}>已退款</div>
      case 3:
        return <div style={{ color: '#f00' }}>已拒绝</div>
      default:
        return null
    }
  }

  const judgeDom = (arr1: [], arr2: any, name: string, val: string | number, val2: string | number) => {
    if (arr1 === arr2) {
      return <span>{name}{val}</span>
    } else {
      return <span>{name}{val2}</span>
    }
  }


  const domFun = (fnName: any) => (
    fnName.map((item: any, index: number) => (
      <div className={styles.cardBox} key={index}>

        {/* 顶部 */}
        <div className={styles.cardTop}>
          <div>订单编号: {item.orderSn}</div>
          {itemStatus(item.status)}
        </div>

        {/* 中间 */}
        <div className={styles.cardCenter}>
          <div className={styles.goodsImgBox} onClick={() => gotoGoodsDetail(item)}>
            {
              item.productPic ?
                <img className={styles.goodsImg} src={item.productPic} alt="img" /> :
                <div>
                  <PictureWrongOutline fontSize={36} />
                </div>
            }
          </div>
          <div className={styles.goodsInfo}>
            <div className={styles.goodsName}>
              <div>{item.productName}</div>
              <div>¥{item.productPrice ? item.productPrice : 0}</div>
            </div>
            <div>
              <div className={styles.numbering}>
                {judgeDom(fnName, afterVal, '编号:', item.id, item.productSn)}
                {judgeDom(fnName, afterVal, 'x ', item.productCount, item.productQuantity)}
              </div>
              <div>
                <span>规格：</span>
              </div>
              <div className={styles.lastSpan}>
                <div>
                  <span>颜色 : {item.productAttr && item.productAttr[0] && item.productAttr[0].value ? item.productAttr[0].value : '未定义'}</span>
                  <span>大小 : {item.productAttr && item.productAttr[1] && item.productAttr[1].value ? item.productAttr[1].value : '未定义'}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 底部 */}
        <div className={styles.cardBottom}>
          {
            fnName === afterVal ?
              <>
                <span>时间: {item.createTime}</span>
                <span>合计: ¥{item.productCount * item.productPrice}</span>
              </> :
              <>
                <span></span>
                <span>合计: ¥{item.productPrice * item.productQuantity}</span>
              </>
          }
        </div>
      </div>
    ))
  )

  // console.log(orderData && orderData.length)
  // console.log(afterVal)
  // console.log(JSON.stringify(orderDataCopy[0]))

  return (
    <>
      {
        orderData && orderData.length !== 0 ?
          orderData.map((item, index) => (
            <div className={styles.cardBox} key={index}>

              {/* 顶部 */}
              <div className={styles.cardTop}>
                <div>订单编号: {item.order.orderSn}</div>
                {
                  type && type === '0' ? <div>未付款</div> :
                    type === '1' ? <div>已付款，等待发货</div> :
                      type === '2' ? <div>已发货</div> :
                        type === '3' ? <div>{item.order.status + '' === '3' ? (<div>已收货</div>) : (<div>已退单</div>)}</div> :
                          type === '6' ? <div>等待支付</div> : null
                }
              </div>

              {/* 中间 */}
              {
                item.items.map((item1, index: number) => (
                  <div className={styles.cardCenter} key={index}>
                    <div className={styles.goodsImgBox} onClick={() => gotoGoodsDetail(item1)}>
                      {
                        item1.productPic ?
                          <img className={styles.goodsImg} src={item1.productPic} alt="img" /> :
                          <div>
                            <PictureWrongOutline fontSize={36} />
                          </div>
                      }
                    </div>
                    <div className={styles.goodsInfo}>
                      <div className={styles.goodsName}>
                        <div>{item1.productName}</div>
                        <div>¥{item1.productPrice ? item1.productPrice : 0}</div>
                      </div>
                      <div>
                        <div className={styles.numbering}>
                          <span>编号：{item1.id}</span>
                          <span>x {item1.productQuantity}</span>
                        </div>
                        <div>
                          <span>规格：</span>
                        </div>
                        <div className={styles.lastSpan}>
                          <div>
                            <span>颜色 : {JSON.parse(item1.productAttr) && JSON.parse(item1.productAttr)[0] && JSON.parse(item1.productAttr)[0].value ? JSON.parse(item1.productAttr)[0].value : '随机'}</span>
                            <span>大小 : {JSON.parse(item1.productAttr) && JSON.parse(item1.productAttr)[1] && JSON.parse(item1.productAttr)[1] ? JSON.parse(item1.productAttr)[1].value : '随机'}</span>
                          </div>

                        </div>
                        {
                          type && type === '2' ?
                            <div className={styles.returnDiv}>
                              {
                                item1.isReturn ?
                                  <span style={{ color: 'red' }}>退货中</span> :
                                  <span onClick={() => returnGoods(item1)}>退货</span>
                              }
                            </div> : null
                        }
                      </div>
                    </div>
                  </div>
                ))
              }


              {/* 底部 */}
              <div className={styles.cardBottom}>
                {
                  item.order.modifyTime ?
                    <div>
                      时间: {item.order.modifyTime}
                    </div> : <div></div>
                }
                <div>合计: ¥{item.order.totalAmount}</div>
              </div>


              {/* 底部操作 */}
              {
                type && type === '0' ?
                  <div className={styles.cancelOrder}>
                    <div onClick={() => cancelGoods(item)}>取消订单</div>
                    <div onClick={() => payBtn(item)}>付款</div>
                  </div> : type === '2' ?
                    <div className={styles.cancelOrder}>
                      <div onClick={() => confirmGoods(item)}>确认收货</div>
                    </div> : type === '3' ?
                      <div className={styles.delOrder}>
                        <div onClick={() => delGoods(item)}>订单已关闭，删除订单</div>
                      </div> : type === '6' ?
                        <div className={styles.cancelOrder}>
                          {/* <div onClick={() => confirmPay(item)}>确认付款1</div> */}
                          <div onClick={() => confirmPay1(item)}>确认付款</div>
                          {/* <div onClick={() => confirmPay2(item)}>确认付款3</div> */}
                        </div> : null
              }

            </div>
          )) :
          afterVal && afterVal.length !== 0 ?
            domFun(afterVal) :
            JSON.stringify(orderDataCopy[0]) !== '{}' ?
              // orderDataCopy.length !== 0 ?
              domFun(orderDataCopy) :
              <div className={styles.notData}>暂无数据</div>
      }
    </>
  )
})

export default OrderCard